﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SendMailServer.Configs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer.Search
{
    internal class ChatGpt
    {
        private IConnection connection = new DifyConection();

        public static Dictionary<string, string> m_userTopicId = new Dictionary<string, string>();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="topicAndChatMsgWithAppName">topic:userName:ChatMsg</param>
        /// <returns></returns>
        public void ChatAsync(string key, string topicAndChatMsgWithAppName,EventHandler handler)
        {
            var e1 = connection.Load(key);
            if(e1 != null) { handler(e1, null); return; }

            try
            {
                string topic;
                string chatMsg;

                var t2 = topicAndChatMsgWithAppName.LastIndexOf(",");
                var topicAndChatMsg = topicAndChatMsgWithAppName.Substring(0, t2);
                var t1 = topicAndChatMsg.IndexOf(":");

                if (t1 == -1)
                {
                    handler(new ResMsg()
                    {
                        MsgCode = key,
                        IsOk = false,
                        Content = "错误的chat输入，应该包含topic和ChatMsg(JSON)",
                        UseSelfResponse = true
                    },null);
                    return;
                }
                topic = topicAndChatMsg.Substring(0, t1);
                var chatMsgWithUser = topicAndChatMsg.Substring(t1 + 1);
                chatMsg = chatMsgWithUser;
                if (topic == "GetAllTopic" || chatMsg == "GetAllTopic")
                {
                    var allTopic = ChatGptConfig.GetAllTopics(out string errorMsg2);
                    handler( new ResMsg()
                    {
                        MsgCode = key,
                        IsOk = errorMsg2 != null,
                        Content = errorMsg2 != null ? errorMsg2 : allTopic,
                        UseSelfResponse = true
                    },null); return;
                }
                var t3 = chatMsgWithUser.IndexOf(':');
                var userName = chatMsgWithUser.Substring(0, t3);
                chatMsg = chatMsgWithUser.Substring(t3 + 1);

                var isOk = ExamHelper.SaveChatGptQuestions(userName, chatMsg, out string errorMsg3);
                if (isOk == false)
                {
                    handler(new ResMsg()
                    {
                        MsgCode = key,
                        IsOk = false,
                        Content = "插入记录出错:" + errorMsg3,
                        UseSelfResponse = true
                    }, null); return;
                }

                var oldAttr = (JToken)JsonConvert.DeserializeObject(chatMsg as string);
                var e2=connection.Reload(key);
                if (e2 != null) { handler(e2,null); return; }

                var er = connection.CreateNewTopic(oldAttr, userName,  key);
                if (er != null) { handler(er, null); return; }

                var msg = oldAttr["query"].ToString();

                connection.ChatAsync(msg, userName, key,handler);
            }
            catch (Exception err)
            {
                handler(new ResMsg()
                {
                    MsgCode = key,
                    IsOk = false,
                    Content = "在地址 " + connection.LastPostUrl + "发生错误," + err.Message + "," + err.StackTrace,
                    UseSelfResponse = true
                },null); return;
            }
        }

        
    }
}
